package com.xianggu.protocol;

import com.alibaba.fastjson2.JSON;
import com.xianggu.spring.XiangGuApplicationContent;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author chengjy
 * @date 2025/3/8
 */
public class RpcServletHandler {
    private XiangGuApplicationContent applicationContent;
    public RpcServletHandler(XiangGuApplicationContent applicationContent) {
        this.applicationContent = applicationContent;
    }

    public void handler(HttpServletRequest req, HttpServletResponse resp) {
                // 这里完成请求的处理逻辑：主要执行本地方法
                try {
                    ObjectInputStream inputStream = new ObjectInputStream(req.getInputStream());
            Invocation invocation = (Invocation) inputStream.readObject();

            // 获取调用对象
//            Class bean = RegisterBeanCont.getBean(invocation.getInterfaceName(), invocation.getVersion());
            // 从Spring容器中获取对象
            Object object = applicationContent.getBean(invocation.getInterfaceName());
            Class<?> bean = invocation.getaClass();

            // 反射调用目标方法
            Method method = bean.getMethod(invocation.getMethodName(), invocation.getParameterTypes());
            // 获取返回值类型
            Object invoke = method.invoke(object, invocation.getArgs());
            String resultJson = JSON.toJSONString(invoke);
            IOUtils.write(resultJson , resp.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("IO异常");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            throw new RuntimeException("readObject异常");
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }


    }
}
